package com.aistudy.file.controller;

import com.aistudy.common.core.domain.R;
import com.aistudy.common.core.utils.file.FileUtils;
import com.aistudy.file.service.IMinioService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

/**
 * Minio文件操作控制器
 *
 * @author aistudy
 */
@RestController
@RequestMapping("/minio")
public class MinioController {
    private static final Logger log = LoggerFactory.getLogger(MinioController.class);

    @Autowired
    private IMinioService minioService;

    /**
     * 文件上传
     */
    @PostMapping("/upload")
    public R<Map<String, String>> upload(MultipartFile file) {
        try {
            // 上传并返回访问地址
            String url = minioService.uploadFile(file);
            Map<String, String> data = new HashMap<>();
            data.put("fileName", FileUtils.getName(url));
            data.put("url", url);
            return R.ok(data);
        } catch (Exception e) {
            log.error("上传文件失败", e);
            return R.fail(e.getMessage());
        }
    }

    /**
     * 获取文件下载链接（带签名的临时URL）
     */
    @GetMapping("/download")
    public R<String> getDownloadUrl(@RequestParam(value = "objectName") String objectName,
                                    @RequestParam(value = "expires", defaultValue = "7200") Integer expires) {
        try {
            String url = minioService.getPresignedObjectUrl(objectName, expires);
            return R.ok(url);
        } catch (Exception e) {
            log.error("获取文件下载链接失败", e);
            return R.fail(e.getMessage());
        }
    }

    /**
     * 删除文件
     */
    @DeleteMapping
    public R<Void> delete(@RequestParam(value = "objectName") String objectName) {
        try {
            minioService.removeObject(objectName);
            return R.ok();
        } catch (Exception e) {
            log.error("删除文件失败", e);
            return R.fail(e.getMessage());
        }
    }

    /**
     * 检查文件是否存在
     */
    @GetMapping("/exists")
    public R<Boolean> exists(@RequestParam(value = "objectName") String objectName) {
        try {
            boolean exists = minioService.checkObjectExist(objectName);
            return R.ok(exists);
        } catch (Exception e) {
            log.error("检查文件是否存在失败", e);
            return R.fail(e.getMessage());
        }
    }
} 